package my.yuan.ms.rediskafkams.controller;

import my.yuan.ms.rediskafkams.controller.vo.MsVO;
import my.yuan.ms.rediskafkams.mapper.cache.RedisMapper;
import my.yuan.ms.rediskafkams.res.CommonReturnType;
import my.yuan.ms.rediskafkams.service.MsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/ms")
public class MSController {
    public final static String PREFIX = "*&)";
    public final static String SUFFIX = "+&*";
    //访问次数限制
    public static int limitCnt = 10;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private MsService msService;
    @Autowired
    RedisMapper redisMapper;

    /**
     * @param userId
     * @return my.yuan.ms.rediskafkams.res.CommonReturnType
     * @Description 通过md5加密后放到redis中自增，获取返回值判断是否大于访问次数限制；是的话拒绝访问，不是的话返回真实URL
     */
    @GetMapping("/getPath")
    public CommonReturnType getPath(@RequestParam("userId") Integer userId) {
        StringBuilder sb = new StringBuilder();
        sb.append(PREFIX).append(userId).append(SUFFIX);
        String s = DigestUtils.md5DigestAsHex(sb.toString().getBytes());
        Long increment = redisTemplate.opsForValue().increment(s);
        if (increment > limitCnt) {
            return CommonReturnType.fail("频繁访问！");
        }
        // 用令牌桶限流（未测试）
        /*boolean isUnderLimit = redisMapper.tokenLimitControl("total:limit", TokenLimiterEm.LOW);
        if (!isUnderLimit) {
            return CommonReturnType.fail("访问量过大！");
        }*/
        return CommonReturnType.success(s);

    }

    /**
     * @Description getPath()返回md5加密的路径，用这个路径进行校验，成功则进行秒杀相关，否则拒绝
     * @param encryt
     * @param msVO
     * @return my.yuan.ms.rediskafkams.res.CommonReturnType
     */
    @PostMapping("/{encryt}/ms")
    public CommonReturnType ms(@PathVariable("encryt") String encryt, @RequestBody MsVO msVO) {
        Integer uid = msVO.getUid();
        StringBuilder sb = new StringBuilder();
        sb.append(PREFIX).append(uid).append(SUFFIX);
        String s = DigestUtils.md5DigestAsHex(sb.toString().getBytes());
        System.out.println(s);
        System.out.println(encryt);

        if (s.equals(encryt)) {
            //进行秒杀步骤
            boolean isMsOk = msService.executeMs(msVO);
            if (isMsOk) {
                return CommonReturnType.success("成功抢到~");
            }
            return CommonReturnType.fail("没有抢到~");
        }

        return CommonReturnType.fail("非法访问！");

    }
}
